package com.aica.util;

import com.aica.constant.EmailMessageConstant;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;


/**
 * 邮件发送工具类
 * @author by
 */
public class EmailUtil {

    private final static String T_CODE = "sgjshyzcawtjdadb";

    /**
     * 创建邮件页面
     * @param sourceAddress 发送方邮箱
     * @param destinationAddress 接收方邮箱
     * @param sourceAddressTestCode 发送方邮箱发送许可码
     * @param sourceName 发送方用户名，可随意填写
     * @return HtmlEmail邮件页面对象
     * @throws EmailException 发送邮箱异常
     */
    public static HtmlEmail creatEmail(String sourceAddress,String destinationAddress,
                                       String sourceAddressTestCode,String sourceName)throws EmailException{
        HtmlEmail email = new HtmlEmail();
        //需要修改，126邮箱为smtp.126.com,163邮箱为163.smtp.com，QQ为smtp.qq.com
        //TODO 后面可以加上正则校验源地址来选择
        email.setHostName("smtp.qq.com");

        email.setCharset("UTF-8");
        //根据具体开放邮件端口设置
        email.setSmtpPort(587);
        // 收件地址
        email.addTo(destinationAddress);

        //此处填邮箱地址和用户名,用户名可以任意填写
        email.setFrom(sourceAddress,sourceName);
        //此处填写邮箱地址和客户端授权码
        email.setAuthentication(sourceAddress, sourceAddressTestCode);

        return email;
    }
    /**
     * 邮箱发送验证码
     * @param emailAddress 目的地邮箱地址
     * @param code 验证码
     * @return 发送成功返回true，反之false
     */
    public static boolean sendVerificationCode(String emailAddress,String code){
        try {

            //创建邮件页面
            HtmlEmail email = creatEmail(
                    EmailMessageConstant.SYSTEM_EMAIL,
                    emailAddress,
                    T_CODE,
                    EmailMessageConstant.SYSTEM_NAME
            );

            ////此处填写邮件名，邮件名可任意填写
            email.setSubject(EmailMessageConstant.TITLE);
            //此处填写邮件内容
            email.setMsg(
                    EmailMessageConstant.THE_FIRST +
                    code +
                    EmailMessageConstant.LIMIT_15_MIN +
                    EmailMessageConstant.THE_LAST
            );
            //发送
            email.send();
            return true;
        } catch (EmailException e) {
            e.printStackTrace();
            return false;
        }
    }
}